import IDValidator from 'id-validator'
import { Component } from '@didi/teddy-immutable'
import FormList from '../form-list/form-list'
import QueryButton from '../query-button/query-button'
import PopLayer from '../pop-layer/pop-layer'
import SelPanel from '../sel-panel/sel-panel'
import tool from '../../common/tool'
import { getStorageSync, setStorage } from '../../common/storage'
import api from '../../api'
import config from '../../config'

const {
  district
} = config
const {
  trim,
  getCaptchaUrl,
  vibrate
} = tool
let region = getStorageSync('region')
let jszh = getStorageSync('jszh')
let dabh = getStorageSync('dabh')

function restoreInfo () {
  const fileds = ['region', 'jszh', 'dabh']

  fileds.forEach((filed) => {
    const val = getStorageSync(filed)
    if (val === undefined || val === '') {
      switch (filed) {
        case 'region':
          region = {
            id: 'bj',
            text: '北京'
          }
          setStorage({
            key: 'region',
            data: region
          })
          break
        case 'jszh':
          jszh = ''
          break
        case 'dabh':
          dabh = ''
          break
        default:
          // do nothing
      }
    } else if (filed === 'region') {
      if (region.id === '') {
        region.id = 'bj'
        region.text = '北京'
      }
    }
  })
}

restoreInfo()

class QueryScore extends Component {
  state = {
    showPop: false,
    showSelPanel: false,
    popDesc: '',
    region,
    isInputShow: true,
    loading: false,
    jszh: '', // 驾驶证号
    dabh: '', // 档案号
    captcha: '',  // 验证码
    captchaSrc: getCaptchaUrl({
      params: {
        region: region.id
      }
    })
  }

  children() {
    const state = this.state
    return {
      selPanel: {
        component: SelPanel,
        props: {
          items: district,
          selKey: 'id',
          selVal: region.id,
          closeSelPanel: () => {
            this.updateSelPanel(false)
          },
          onSel: (item) => {
            this.updateSelPanel(false)
            if (item.id === this.state.region.id) {
              return
            }
            this.bindDistrictChange(item)
          }
        }
      },
      popLayer: {
        component: PopLayer,
        props: {
          desc: state.popDesc,
          onBtnTap: () => {
            this.setState({
              showPop: false
            })
          }
        }
      },
      queryButton: {
        component: QueryButton,
        props: {
          loading: state.loading,
          onTap: () => {
            this.doScoreQuery()
          }
        }
      },
      headerList: {
        component: FormList,
        props: {
          items: [
            {
              type: 'picker',
              title: '选择驾驶证注册地：',
              val: state.region.text,
              showArrow: true,
              onTap: () => {
                this.updateSelPanel(true)
              }
            }
          ]
        }
      },
      licenseList: {
        component: FormList,
        props: {
          items: [
            {
              title: '驾驶证号：',
              name: 'jszh',
              inputType: 'idcard',
              isInputShow: state.isInputShow,
              maxlength: '18',
              val: jszh,
              onInput: (e) => {
                this.onInput(e)
              }
            },
            {
              title: '档案编号：',
              name: 'dabh',
              maxlength: '12',
              isInputShow: state.isInputShow,
              val: dabh,
              onInput: (e) => {
                this.onInput(e)
              }
            }
          ]
        }
      },
      footerList: {
        component: FormList,
        props: {
          items: [
            {
              type: 'captcha',
              title: '验证码：',
              name: 'captcha',
              inputType: 'text',
              isInputShow: state.isInputShow,
              src: this.state.captchaSrc,
              maxlength: '4',
              val: '',
              onInput: (e) => {
                this.onInput(e)
              },
              onCaptchaTap: () => {
                this.onCaptchaTap()
              }
            }
          ]
        }
      },
    }
  }

  // 驾照注册地 picker 变化监听
  bindDistrictChange(region) {
    // 注册地变了，需要重新种 cookie
    this.setCaptchaUrl(region.id)
    this.setState({ region })
    setStorage({
      key: 'region',
      data: region
    })
  }

  onInput(e) {
    const name = e.currentTarget.dataset.name
    const value = e.detail.value
    this.setState({ [name]: value })
    
    // 存储非验证码的字段
    if (name !== 'captcha') {
      setStorage({
        key: name,
        data: value
      })
    }
  }

  setCaptchaUrl(region) {
    this.setState({
      captchaSrc: getCaptchaUrl({
        params: {
          region: region || this.state.region.id
        }
      })
    })
  }

  onCaptchaTap() {
    this.setCaptchaUrl()
  }

  doScoreQuery() {
    if (!this.doValidate()) {
      return
    }
    this.updateLoading(true)
    const state = this.state
    // 查询驾照扣分信息
    api.queryScore({
      params: {
        region: state.region.id,
        jszh: state.jszh,
        dabh: state.dabh,
        captcha: state.captcha
      },
      success: (data) => {
        this.updateLoading(false)
        // 震动提示
        vibrate()
        const {
          ljjf
        } = data
        const popDesc = `当前记分周期内已扣 ${ljjf} 分`
        this.setState({
          popDesc,
          showPop: true
        })
      },
      fail: () => {
        this.updateLoading(false)
      }
    })
  }

  updatePopLayer(isShow) {
    this.setState({
      showPop: isShow
    })
  }

  updateSelPanel(isShow) {
    this.setState({
      showSelPanel: isShow
    })
  }

  updateLoading(isLoading) {
    this.setState({
      loading: isLoading
    })
  }

  // 信息校验
  doValidate() {
    const state = this.state
    const fileds = ['jszh', 'dabh', 'captcha']
    const jszh = trim(state.jszh)
    const captcha = trim(state.captcha)
    const dabh = trim(state.dabh)
    const regCaptcha = /^[\d\w]{4}$/
    const regDabh = /^\d{12}$/
    const emptyTipMap = {
      jszh: '驾驶证号',
      dabh: '档案编号',
      captcha: '验证码'
    }
    const showToast = (title) => {
      wx.showToast({
        title
      })
    }

    for (const filed in fileds) {
      if (trim(state[filed])) {
        showToast(`${emptyTipMap[filed]}不能为空`)
        return false
      }
    }

    const Validator = new IDValidator()
    console.log(jszh)
    if (!Validator.isValid(jszh)) {
      showToast('请输入合法驾驶证号')
      return false
    }

    if (!regDabh.test(dabh)) {
      showToast('请输入 12 位档案编号')
      return false
    }

    if (!regCaptcha.test(captcha)) {
      showToast('请输入四位验证码')
      return false
    }

    return true
  }

  onLoad() {
    this.setState({
      region,
      jszh,
      dabh
    })
  }
}

export default QueryScore
